package com.bsi.core.authorization;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/*
 * Author: liusongs
 * Date: 2019/12/16 11:17
 * Content: 根据userId去redis中获取当前用户
 */
public class RequestUtils implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtils.class);
    private static ApplicationContext APPLICATION_CONTEXT;
    private static String USER_ID;

    private static RedisTemplate REDIS_TEMPLATE = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        APPLICATION_CONTEXT = applicationContext;
        REDIS_TEMPLATE = (RedisTemplate) applicationContext.getBean("redisTemplate");
    }

    public void setUserId(String userId) {
        USER_ID = userId;
    }

    /**
     * 原因：
     * Class<T>  获取系统登陆用户（此工程只能传入CmUser类）。用泛型的原因是common-core工程是只为框架的工具类等开箱即用的工程。
     * 而如果直接传入实体类或者直接在此方法中将user类写入进去，则会造成此工程会与common-mapper工程（封装mapper与entity类的工程）进行关联。
     * 这样则会造成common-core工程与common-mapper工程有耦合状态，会违背了我创建common-core工程放在哪都能用的初心。故抽成泛型
     *
     * @return
     */
    public static <T> T getCurrentUser(Class<T> tClass) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String id = request.getHeader(USER_ID);
        if (StringUtils.isEmpty(id)) {
            LOGGER.error("[RequestUtils.getCurrentUser]调用失败，当前request中未包含userId这个请求头");
            return null;
        }
        return (T) REDIS_TEMPLATE.opsForValue().get(id);
    }


    //根据类型获取缓存信息
    public static <T> List<T> getSomeListFromUser(Class<T> tClass, String key) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String id = request.getHeader(USER_ID);
        //LOGGER.info("用户id:"+id);
        if (StringUtils.isEmpty(id)) {
            LOGGER.error("[RequestUtils.getCurrentUser]调用失败，当前request中未包含userId这个请求头！");
            return null;
        }
        //LOGGER.info("redis用户信息:"+redisTemplate.opsForValue().get(id + key));
        return (List<T>) REDIS_TEMPLATE.opsForValue().get(id + key);
    }

}
